package com.example.finalassignment;

import com.example.finalassignment.common.Cache;
import com.example.finalassignment.common.Constant;
import com.example.finalassignment.mapper.FilesMapper;
import com.example.finalassignment.pojo.Files;
import jakarta.annotation.PreDestroy;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.Set;

@SpringBootApplication
@MapperScan("com.example.finalassignment.mapper")
public class FinalAssignmentApplication implements ApplicationRunner {

    private final FilesMapper filesMapper;

    public FinalAssignmentApplication(FilesMapper filesMapper) {
        this.filesMapper = filesMapper;
    }

    public static void main(String[] args) {
        SpringApplication.run(FinalAssignmentApplication.class, args);
    }

    /**
     * 项目启动时执行
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        initCachePicture();
        initUserCache();
    }

    /**
     * 项目关闭时执行
     */
    @PreDestroy
    public void destroy() throws FileNotFoundException {
        saveUserCache();
    }

    /**
     * 保存userToken
     */
    private void saveUserCache() throws FileNotFoundException {
        Set<String> keys = Cache.USER_INFO.keySet();
        StringBuffer sb = new StringBuffer("");
        for (String key : keys) {
            sb.append(key);
            sb.append(",");
        }

        String url = Constant.PROJECT_URL + "/src/main/java/com/example/finalassignment/record/UserToken.txt";

        File file = new File(url);

        PrintWriter printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))));
        printWriter.println(sb);
        printWriter.flush();
        printWriter.close();
    }

    /**
     * 将默认的头像放入缓存中
     */
    private void initCachePicture() {
        List<Files> dataByDefault = filesMapper.getDataByDefault();
        List<String> pictureCache = Cache.PICTURE_CACHE;
        for (Files file : dataByDefault) {
            pictureCache.add(file.getUuid());
        }

        System.out.println("初始化头像:" + Cache.PICTURE_CACHE);
    }

    /**
     * 读取之前登录过的用户
     */
    private void initUserCache() throws IOException {
        String url = Constant.PROJECT_URL + "/src/main/java/com/example/finalassignment/record/UserToken.txt";
        File file = new File(url);
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

        String[] strings = br.readLine().split(",");

        for(String token : strings){
            Cache.USER_INFO.put(token,"");
        }

        System.out.println("初始化token:" + Cache.USER_INFO);
        br.close();
    }
}
